//
//  PersistentController.swift
//  TomatoClock
//
//  Created by DaleGuo on 2023/11/21.
//

import Foundation

import CoreData

struct PersistentController {
    static let shared = PersistentController()
    let container: NSPersistentContainer
    
    var viewContext: NSManagedObjectContext {
        return container.viewContext
    }

    
    init(inMemory: Bool = false) {
        container = NSPersistentContainer(name: "tomatoClock")
        
        let url = URL.storeURL(for: "group.com.dale.tomato_clock", databaseName: "tomatoClock")
        
        let storeDescription = NSPersistentStoreDescription(url: url)
        
        container.persistentStoreDescriptions = [storeDescription]
        
        if inMemory {
            container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
        }
        
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        container.viewContext.automaticallyMergesChangesFromParent = true
    }
}

public extension URL {
    static func storeURL(for appGroup : String, databaseName:String) -> URL {
        guard let fileContainer = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup) else {
            fatalError("Unable to load database")
        }
        
        return fileContainer.appendingPathComponent("\(databaseName).sqlite")
    }
}
